#include <iostream>
#include <string>
#include <unistd.h>

using namespace std;

int ticket = 1000;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* ThreadRoutine(void* arg)
{
    string threadname = (const char*)arg;

    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(ticket > 0)
        {
            cout << threadname << " get a ticket : " << ticket-- << endl;
        }
        else
        {
            cout << threadname << " : 没票了" << endl;
            pthread_cond_wait(&cond,&mutex);
        }
        pthread_mutex_unlock(&mutex);
    }

    return nullptr;
}

int main()
{
    pthread_t t1,t2,t3;
    pthread_create(&t1,nullptr,ThreadRoutine,(void*)"thread-1");
    pthread_create(&t2,nullptr,ThreadRoutine,(void*)"thread-2");
    pthread_create(&t3,nullptr,ThreadRoutine,(void*)"thread-3");

    while(1)
    {
        sleep(5);
        pthread_mutex_lock(&mutex);
        ticket += 1000;
        pthread_mutex_unlock(&mutex);

        pthread_cond_broadcast(&cond);
        // pthread_cond_signal(&cond);
    }

    pthread_join(t1,nullptr);
    pthread_join(t2,nullptr);
    pthread_join(t3,nullptr);

    return 0;
}

